//
//  Mo.swift
//  iPhone
//
//  Created by Toj on 6/14/22.
//

import UIKit
import HandyJSON

public protocol STJSONCodable: HandyJSON { }

extension STJSONCodable {
    
//    /* 序列化: 将对象转字典数据 */
//    var objc_json: [String: Any]? {
//        return toJSON()
//    }
//    
//    /* 序列化: 将对象转字符串数据 */
//    var objc_serializeString: String? {
//        return toJSONString()
//    }
}

extension Dictionary where Key == String, Value == Any {
    
    /* 反序列化: 将数据转对象 */
    func json_deserialize<T: STJSONCodable>() -> T? {
        let rModel = T.deserialize(from: self)
        return rModel
    }
    
    /* 反序列化: 讲数据转对象 */
    func json_deserialize<T: STJSONCodable>(model T: T.Type) -> T? {
        let rModel = T.deserialize(from: self)
        return rModel
    }
}

extension Array {
    
    /* 反序列化: 将数据转对象 */
    func json_deserialize<T: STJSONCodable>() -> [T?]? {
        let rModels = [T].deserialize(from: self)
        return rModels
    }
    
    /* 反序列化: 讲数据转对象 */
    func json_deserialize<T: STJSONCodable>(model T: T.Type) -> [T] {
        let rModels = Array<T>.deserialize(from: self)
        
        var models: [T] = []
        rModels?.forEach({ model in
            guard let m = model else { return }
            models.append(m)
        })
        
        return models
    }
}

extension String {
    
    /* 反序列化: 将数据转对象 */
    func json_deserialize<T: STJSONCodable>() -> T? {
        let rModel = T.deserialize(from: self)
        return rModel
    }
    
    /* 反序列化: 讲数据转对象 */
    func json_deserialize<T: STJSONCodable>(model T: T.Type) -> T? {
        let rModel = T.deserialize(from: self)
        return rModel
    }
}

extension NSObject:   STJSONCodable { }
extension String:     STJSONCodable { }
extension Array:      STJSONCodable { }
extension Set:        STJSONCodable { }
extension Dictionary: STJSONCodable { }

open class STResponse<Element>: NSObject {
    public var code = 0
    public let data: Element? = nil
    public var message = ""
    public var traceId = ""
    
    deinit {
        print(className + " : " + #function )
    }
}

extension STResponse {
  
}

extension NSObject {
    #if canImport(UIKit)
    fileprivate var className: String {
        return NSStringFromClass(classForCoder)
    }
    #endif
}
